import smtplib
import time
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.utils import formataddr
import ssl

# pip install schedule
import schedule as schedule

# 配置信息
qq_mail = '793757152@qq.com'  # 替换为你的QQ邮箱
qq_password = 'wnqbdnxyzqphbfeh'  # 替换为QQ邮箱授权码
mail_163 = 'yrqc53719@163.com'  # 替换为收件人163邮箱

# 邮件内容
subject = 'Python邮件测试'
# html类型
content = """
<html>
<body>
    <h2>这是一封带附件的测试邮件</h2>
    <p>使用Python发送的邮件，包含附件。</p>
</body>
</html>
"""
# 普通文本类型
# content = 'nihao'

# 创建邮件对象
message = MIMEMultipart()
message['From'] = formataddr(('发送者名称', qq_mail))  # 严格遵循RFC标准
message['To'] = formataddr(('接收者名称', mail_163))  # 规范收件人格式
message['Subject'] = Header(subject, 'utf-8')  # 主题编码
# 发送附件
# 添加附件1（文本文件）
with open('1. 单个发送邮件.py', 'rb') as f:
    attach_part = MIMEApplication(f.read(), Name='1. 单个发送邮件.py')
    attach_part['Content-Disposition'] = 'attachment; filename="1. 单个发送邮件.py"'
    message.attach(attach_part)

# # 添加附件2（图片文件）
# with open('image.jpg', 'rb') as f:
#     attach_part = MIMEApplication(f.read(), Name='image.jpg')
#     attach_part['Content-Disposition'] = 'attachment; filename="image.jpg"'
#     message.attach(attach_part)
#
# # 添加附件3（PDF文件）
# with open('document.pdf', 'rb') as f:
#     attach_part = MIMEApplication(f.read(), Name='document.pdf')
#     attach_part['Content-Disposition'] = 'attachment; filename="document.pdf"'
#     message.attach(attach_part)
# html类型
message.attach(MIMEText(content, 'html', 'utf-8'))
# 普通文本类型
# message.attach(MIMEText(content, 'plain', 'utf-8'))
def send():
    print('send start')
    try:
        context = ssl.create_default_context()
        # 1. 连接SMTP服务器（QQ邮箱SSL端口465）
        with smtplib.SMTP_SSL('smtp.qq.com', 465, context=context) as smtp_obj:
            # smtp_obj.set_debuglevel(1)  # 开启调试模式（显示详细日志）

            # 2. 登录邮箱
            smtp_obj.login(qq_mail, qq_password)

            # 3. 发送邮件
            smtp_obj.sendmail(qq_mail, [mail_163], message.as_string())
            print("✅ 邮件发送成功！")

    except Exception as e:
        print(f"❌ 邮件发送失败: {e}")

if __name__ == '__main__':
    schedule.every(10).seconds.do(send)

    while 1:
        schedule.run_pending()
        time.sleep(1)